﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using WP7Client.ServerManager;
using WP7Client.Helpers;
using MSH.Common.DAO.Results;
using System.Collections.Generic;
using MSH.Common.Classes;
using MSH.Common.DAO;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight.Command;
using Microsoft.Phone.Tasks;

namespace WP7Client.Controller
{
    public class InvitationController : BaseController
    {
        PhoneNumberChooserTask numberChooser;

        private ObservableCollection<Friend> invitations = new ObservableCollection<Friend>();

        public InvitationController() 
        {
            AcceptInvitationCommand = new RelayCommand<String>(AcceptInvitation);
            DeclineInvitationCommand = new RelayCommand<String>(DeclineInvitation);
            AddFriendByPhoneContactCommand = new RelayCommand(AddFriendByPhoneContact);
            ShowProfileCommand = new RelayCommand<String>(DoShowProfile);

            numberChooser = new PhoneNumberChooserTask();
            numberChooser.Completed += new EventHandler<PhoneNumberResult>(numberChooser_Completed);
        }

        void numberChooser_Completed(object sender, PhoneNumberResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                Loading = true;
                HttpGet addFriendByPhoneNumberHttpGet = new HttpGet(String.Format(GlobalHelper.Url + "AddFriendByPhoneNumber/{0}/{1}", UserHelper.Token, e.PhoneNumber), typeof(AddFriendByPhoneNumberResult));
                addFriendByPhoneNumberHttpGet.FinishedGet += addFriendByPhoneNumberHttpGet_FinishedGet;
            }
        }

        void addFriendByPhoneNumberHttpGet_FinishedGet(object sender, EventArgs e)
        {
            try
            {
                HttpGet get = sender as HttpGet;
                if (get != null && (get.resultObject as AddFriendByPhoneNumberResult) != null)
                {
                    AddFriendByPhoneNumberResult result = get.resultObject as AddFriendByPhoneNumberResult;
                    if (result.TokenValidationResult == TokenValidationResultEnum.Valid)
                    {
                        switch (result.Result)
                        {
                            case AddFriendByPhoneNumberResultEnum.FriendAlreadyRegistered:
                                GlobalHelper.ShowMessage("Error", "Person is already a friend of yours or you have already received/sent an invitation to this person.");
                                break;
                            case AddFriendByPhoneNumberResultEnum.Succes:
                                GlobalHelper.ShowMessage("", "Invitation has been sent.");
                                break;
                            case AddFriendByPhoneNumberResultEnum.UserNotExists:
                                GlobalHelper.ShowMessage("Error", "User doesn't exists.");
                                break;
                        }
                    }
                }
            }
            finally
            {
                Loading = false;
            }
        }

        public ObservableCollection<Friend> Invitations
        {
            get { return invitations; }
            set
            {
                invitations = value;
                OnPropertyChanged("Invitations");
            }
        }

        public ICommand AcceptInvitationCommand
        {
            get;
            internal set;
        }

        public ICommand DeclineInvitationCommand
        {
            get;
            internal set;
        }

        public ICommand AddFriendByPhoneContactCommand
        {
            get;
            internal set;
        }

        public ICommand ShowProfileCommand
        {
            get;
            internal set;
        }

        public override void Update()
        {
            GetInvitations();
            base.Update();
        }

        /// <summary>
        /// Opvragen van een lijst met inkomende uitnodigingen
        /// </summary>
        private void GetInvitations()
        {
            Loading = true;
            HttpGet invitationsHttpGet = new HttpGet(String.Format(GlobalHelper.Url + "GetFriendInvitations/{0}", UserHelper.Token), typeof(GetFriendInvitationsResult));
            invitationsHttpGet.FinishedGet += invitationsHttpGet_FinishedGet;
        }

        private void invitationsHttpGet_FinishedGet(Object sender, EventArgs e) 
        {
            try
            {
                HttpGet get = sender as HttpGet;
                if(get != null && (get.resultObject as GetFriendInvitationsResult) != null)
                {
                    GetFriendInvitationsResult result = get.resultObject as GetFriendInvitationsResult;
                    if (result.TokenValidationResult == TokenValidationResultEnum.Valid && result.Friends != null)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                           Invitations.Clear();
                           foreach (Friend friend in result.Friends)
                               Invitations.Add(friend);
                        });
                    }
                }
            }
            catch (Exception ex) { }
            finally { Loading = false; }
        }

        /// <summary>
        /// Accepteren van een uitnodiging
        /// </summary>
        /// <param name="username">Gebruikersnaam van gebruiker die de uitnodiging verstuurd heeft</param>
        private void AcceptInvitation(String username)
        {
            Loading = true;
            HttpGet acceptInvitation = new HttpGet(String.Format(GlobalHelper.Url + "AcceptFriendInvitation/{0}/{1}", UserHelper.Token, username), typeof(AcceptFriendInvitationResult));
            acceptInvitation.FinishedGet += AcceptInvitation_FinishedGet;
        }

        /// <summary>
        /// Afwijzen van een vriendverzoek
        /// </summary>
        /// <param name="username">Gebruikersnaam van de gebruiker die de uitnodiging verstuurd heeft</param>
        private void DeclineInvitation(String username)
        {
            Loading = true;
            HttpGet declineInvitation = new HttpGet(String.Format(GlobalHelper.Url + "DeclineFriendInvitation/{0}/{1}", UserHelper.Token, username), typeof(DeclineFriendInvitationResult));
            declineInvitation.FinishedGet += DeclineInvitation_FinishedGet;
        }

        private void AcceptInvitation_FinishedGet(object sender, EventArgs e)
        {
            try
            {
                HttpGet get = sender as HttpGet;
                if (get != null && (get.resultObject as AcceptFriendInvitationResult) != null)
                {
                    AcceptFriendInvitationResult result = get.resultObject as AcceptFriendInvitationResult;

                    if (result.TokenValidationResult == TokenValidationResultEnum.Valid && result.Result != null)
                    {
                        switch (result.Result)
                        {
                            case AcceptFriendInvitationResultEnum.AlreadyAccepted:
                                GlobalHelper.ShowMessage("Error", "This user is already your friend.");
                                break;
                            case AcceptFriendInvitationResultEnum.NoOpenInvitation:
                                GlobalHelper.ShowMessage("Error", "No invitation found.");
                                break;
                            case AcceptFriendInvitationResultEnum.Succes:
                                GlobalHelper.ShowMessage("", "Succesfully accepted.");
                                ControllerHelper.InvitationController.Update();
                                ControllerHelper.FriendController.Update();
                                break;
                            case AcceptFriendInvitationResultEnum.UserNotExists:
                                GlobalHelper.ShowMessage("", "User doesn't exist.");
                                break;
                        }
                    }
                    else if(result.TokenValidationResult == TokenValidationResultEnum.Invalid)
                    {

                    }
                }
            }
            catch (Exception ex) { }
            finally { Loading = false; }
        }

        private void DeclineInvitation_FinishedGet(object sender, EventArgs e)
        {
            try
            {
                HttpGet get = sender as HttpGet;
                if (get != null && (get.resultObject as DeclineFriendInvitationResult) != null)
                {
                    DeclineFriendInvitationResult result = get.resultObject as DeclineFriendInvitationResult;

                    if (result.TokenValidationResult == TokenValidationResultEnum.Valid && result.Result != null)
                    {
                        switch (result.Result)
                        {
                            case DeclineFriendInvitationResultEnum.AlreadyAccepted:
                                GlobalHelper.ShowMessage("Error", "Already your friend");
                                break;
                            case DeclineFriendInvitationResultEnum.NoOpenInvitation:
                                GlobalHelper.ShowMessage("Error", "No invitation found");
                                break;
                            case DeclineFriendInvitationResultEnum.Succes:
                                GlobalHelper.ShowMessage("", "Succesfully declined.");
                                ControllerHelper.InvitationController.Update();
                                break;
                            case DeclineFriendInvitationResultEnum.UserNotExists:
                                GlobalHelper.ShowMessage("", "User doesn't exist.");
                                break;
                        }
                    }
                    else if (result.TokenValidationResult == TokenValidationResultEnum.Invalid)
                    {

                    }
                }
            }
            catch (Exception ex) { }
            finally { Loading = false; }
        }

        /// <summary>
        /// Voeg een vriend toe aan de hand van zijn telefoonnnummer
        /// </summary>
        private void AddFriendByPhoneContact()
        {
            numberChooser.Show();
        }

        /// <summary>
        /// Toon het profiel van de gebruiker die de uitnodiging verstuurd heeft
        /// </summary>
        /// <param name="username">Gebruikersnaam van gebruiker die de uitnodiging verstuurd heeft</param>
        private void DoShowProfile(String username)
        {
            NavigationHelper.NavigateTo(String.Format("/UserInterface/Pages/ProfilePage.xaml?username={0}", username));
        }
    }
}
